// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  globalData: {
    appid: 'wx2cd7120426ce7ee6',
    rootUrl: 'https://dangyang.dtty.tech'
    // rootUrl: 'https://project.unionstart.work'
    // rootUrl: 'http://my.dangyang.com'
  },

  getParams(key){
    return wx.getStorageSync(key);
  },

  selectPhoneNumber(str) {
    var regx = /(1[3|4|5|7|8][\d]{9}|0[\d]{2,3}-[\d]{7,8}|400[-]?[\d]{3}[-]?[\d]{4})/g;
    var phoneNums = str.match(regx);
    if (phoneNums) {
      for (var i = 0; i < phoneNums.length; i++) {
        var temp = phoneNums[i]
      }
    }
    return temp;
  },

  request(method, url, data) {
    console.log('请求url', `${this.globalData.rootUrl}${url}`);
    console.log('请求参数', data);
    let cookie = this.getParams('cookie');
    // if(method == 'post'){
    //   let f = new FormData();
    //   for(let key in data){
    //     f.append(key, data[key]);
    //   }
    //   data = f;
    // }
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.rootUrl + url,
        method: method,
        data: method == 'post' ? data : {},
        header: {
          // 'content-type': 'application/json',
          'content-type': 'application/x-www-form-urlencoded',
          'cookie': cookie ? cookie : ''
        },
        success: (res) => {
          console.log('返回数据', res);
          if(200 == res.statusCode){
            if(0 == res.data.code) resolve(res);
            else if(1 == res.data.code){
              wx.clearStorageSync();
              wx.navigateTo({ url: '/pages/login/login' });
            }else if(202 == res.data.code){
              this.showFailToast(res.data.msg);
            }
            else this.showFailToast('获取数据失败');
          }
          else this.showFailToast('网络错误，请稍后再试');
        },
        fail: res => reject(res)
      });
    });
  },

  showFailToast(title){
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 1500
    });
  },

  showSuccessToast(title){
    wx.showToast({
      title: title,
      icon: 'success',
      duration: 1500
    });
  }



})
